package com.lw.leetcode.arr.b;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * 1679. K 和数对的最大数目
 *
 * @author liw
 * @version 1.0
 * @date 2022/1/17 21:05
 */
public class MaxOperations {

    public static void main(String[] args) {
        MaxOperations test = new MaxOperations();

        // 2
        int[] arr = {1, 2, 3, 4};
        int k = 5;

        int i = test.maxOperations(arr, k);
        System.out.println(i);
    }

    public int maxOperations(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            map.merge(num, 1, (a, b) -> a + b);
        }
        int count = 0;
        for (int num : nums) {
            int c = map.get(num);
            if (c == 0) {
                continue;
            }
            map.put(num, c - 1);
            Integer integer = map.get(k - num);
            if (integer == null || integer == 0) {
                continue;
            }
            count++;
            map.put(k - num, integer - 1);
        }
        return count;
    }

}
